package com.education.ai.controller;

import com.education.ai.entity.Exercise;
import com.education.ai.entity.Student;
import com.education.ai.entity.StudentPracticeSession;
import com.education.ai.entity.StudentMistakeCollection;
import com.education.ai.model.dto.*;
import com.education.ai.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Set;
import java.util.Collections;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;

/**
 * 学生控制器 - 提供学生端所需的API接口
 */
@RestController
@RequestMapping("/api/student")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
public class StudentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;
    
    @Autowired
    private ExerciseService exerciseService;
    
    @Autowired
    private AiTeachingService aiTeachingService;
    
    @Autowired
    private StudentPracticeService studentPracticeService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取学生个人信息
     */
    @GetMapping("/profile")
    public ResponseEntity<?> getStudentProfile(@RequestHeader("Authorization") String token) {
        try {
            Student student = studentService.getCurrentStudent(token);
            return ResponseEntity.ok(student);
        } catch (Exception e) {
            logger.error("获取学生信息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取学生信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取学生的学习进度和表现
     */
    @GetMapping("/learning-progress")
    public ResponseEntity<?> getLearningProgress(@RequestHeader("Authorization") String token) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            Map<String, Object> progressData = studentService.getStudentLearningProgress(studentId);
            return ResponseEntity.ok(progressData);
        } catch (Exception e) {
            logger.error("获取学习进度失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取学习进度失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取推荐练习题
     */
    @GetMapping("/recommended-exercises")
    public ResponseEntity<?> getRecommendedExercises(
            @RequestHeader("Authorization") String token,
            @RequestParam String subject,
            @RequestParam(required = false) String knowledgePoint,
            @RequestParam(required = false, defaultValue = "10") Integer count,
            @RequestParam(required = false) String difficulty) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            logger.info("获取推荐练习题 - 学生ID: {}, 学科: {}, 知识点: {}, 数量: {}, 难度: {}", 
                    studentId, subject, knowledgePoint, count, difficulty);
            
            // 根据参数查询不同的习题
            List<Exercise> exercises;
            
            if (knowledgePoint != null && !knowledgePoint.isEmpty()) {
                // 有知识点参数，使用知识点查询
                exercises = studentService.getRecommendedExercises(studentId, subject, knowledgePoint);
            } else {
                // 无知识点参数，使用通用推荐
                exercises = exerciseService.getRecommendedExercises(studentId, count);
                
                // 如果指定了学科，过滤结果
                if (subject != null && !subject.isEmpty()) {
                    exercises = exercises.stream()
                            .filter(e -> subject.equals(e.getSubject()))
                            .collect(Collectors.toList());
                }
                
                // 如果指定了难度，过滤结果
                if (difficulty != null && !difficulty.isEmpty()) {
                    exercises = exercises.stream()
                            .filter(e -> difficulty.equals(e.getDifficulty()))
                            .collect(Collectors.toList());
                }
                
                // 如果过滤后的结果数量不足，则补充
                if (exercises.size() < count) {
                    List<Exercise> supplementExercises = exerciseService.getExercisesBySubject(subject);
                    
                    // 排除已有的习题
                    Set<Long> existingIds = exercises.stream()
                            .map(Exercise::getId)
                            .collect(Collectors.toSet());
                    
                    supplementExercises = supplementExercises.stream()
                            .filter(e -> !existingIds.contains(e.getId()))
                            .collect(Collectors.toList());
                    
                    // 过滤难度
                    if (difficulty != null && !difficulty.isEmpty()) {
                        supplementExercises = supplementExercises.stream()
                                .filter(e -> difficulty.equals(e.getDifficulty()))
                                .collect(Collectors.toList());
                    }
                    
                    // 随机排序并补充不足的数量
                    Collections.shuffle(supplementExercises);
                    int needed = count - exercises.size();
                    if (needed > 0 && !supplementExercises.isEmpty()) {
                        exercises.addAll(supplementExercises.subList(0, Math.min(needed, supplementExercises.size())));
                    }
                }
                
                // 如果结果超过请求数量，裁剪
                if (exercises.size() > count) {
                    exercises = exercises.subList(0, count);
                }
            }
            
            if (exercises.isEmpty()) {
                logger.warn("未找到符合条件的习题 - 学生ID: {}, 学科: {}", studentId, subject);
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "未找到符合条件的习题，请尝试其他条件");
                return ResponseEntity.ok(response);
            }
            
            logger.info("成功获取{}道推荐习题", exercises.size());
            return ResponseEntity.ok(exercises);
        } catch (Exception e) {
            logger.error("获取推荐练习题失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取推荐练习题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 提交练习答案
     */
    @PostMapping("/submit-practice")
    public ResponseEntity<?> submitPractice(
            @RequestHeader("Authorization") String token,
            @RequestBody PracticeSubmissionRequest submission) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            logger.info("提交练习答案 - 学生ID: {}, 学科: {}, 知识点: {}, 正确题数: {}/{}, 用时: {}秒", 
                    studentId, submission.getSubject(), 
                    submission.getKnowledgePoint(), submission.getCorrectCount(), 
                    submission.getTotalCount(), submission.getCompletionTime());
            
            // 创建新的练习会话记录
            StudentPracticeSession session = StudentPracticeSession.builder()
                .studentId(studentId)
                .subject(submission.getSubject())
                .knowledgePoint(submission.getKnowledgePoint())
                .difficulty(submission.getDifficulty())
                .practiceType(submission.getPracticeType())
                .correctCount(submission.getCorrectCount())
                .totalCount(submission.getTotalCount())
                .completionTime(submission.getCompletionTime())
                .startTime(LocalDateTime.now().minusSeconds(submission.getCompletionTime()))
                .endTime(LocalDateTime.now())
                .build();
            
            // 计算准确率
            if (session.getTotalCount() > 0) {
                session.setAccuracy((double) session.getCorrectCount() / session.getTotalCount());
            }
            
            // 保存会话并获取分析结果
            Map<String, Object> result = studentPracticeService.savePracticeSession(session, submission.getAnswers());
            
            // 返回分析结果和建议
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("提交练习答案失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "提交练习答案失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取错题本
     */
    @GetMapping("/mistake-collection")
    public ResponseEntity<?> getMistakeCollection(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) String subject) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            List<StudentMistakeCollection> mistakes = studentPracticeService.getMistakeCollection(studentId, subject);
            return ResponseEntity.ok(mistakes);
        } catch (Exception e) {
            logger.error("获取错题本失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取错题本失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
            }
    }
    
    /**
     * 获取AI学习助手反馈
     */
    @PostMapping("/ai-assistant")
    public ResponseEntity<?> getAiAssistant(
            @RequestHeader("Authorization") String token,
            @RequestBody AiAssistantRequest request) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            logger.info("收到AI学习助手请求 - 学生ID: {}, 学科: {}, 问题: {}", 
                    studentId, request.getSubject(), request.getQuestion());
            
            // 获取学生表现数据（如果有）
            Map<String, Object> performanceData = new HashMap<>();
            
            // 检查是否有已传入的学生表现数据
            if (request.getStudentPerformance() != null) {
                // 转换学生表现数据
                AiAssistantRequest.StudentPerformanceDto performance = request.getStudentPerformance();
                performanceData.put("averageScore", performance.getAverageScore());
                performanceData.put("completedExercises", performance.getCompletedExercises());
                performanceData.put("studyTime", performance.getStudyTime());
                performanceData.put("mistakeCount", performance.getMistakeCount());
                performanceData.put("recentPractices", performance.getRecentPractices());
                
                logger.info("前端传递的学生表现数据: {}", performanceData);
            } else {
                logger.warn("未收到前端学生表现数据，尝试从数据库获取");
            }
            
            // 获取学生学科成绩数据（从考试记录表）
            try {
                String subjectField = convertSubjectNameToField(request.getSubject());
                if (subjectField != null) {
                    String scoreSql = "SELECT AVG(" + subjectField + ") as average FROM exam_records WHERE student_id = ?";
                    Double averageScore = jdbcTemplate.queryForObject(scoreSql, Double.class, studentId);
                    
                    if (averageScore != null) {
                        logger.info("查询到学生 {} 在 {} 学科的平均成绩: {}", studentId, request.getSubject(), averageScore);
                        performanceData.put("averageScore", averageScore);
        } else {
                        logger.warn("未找到学生 {} 在 {} 学科的成绩记录", studentId, request.getSubject());
                    }
                }
            } catch (Exception e) {
                logger.error("获取学生学科成绩失败", e);
            }
            
            // 获取练习会话数据
            try {
                String sessionSql = "SELECT COUNT(*) FROM student_practice_sessions WHERE student_id = ? AND subject = ?";
                Integer sessionCount = jdbcTemplate.queryForObject(
                        sessionSql, Integer.class, studentId, request.getSubject());
                
                if (sessionCount != null && sessionCount > 0) {
                    logger.info("查询到学生 {} 在 {} 学科的练习会话数: {}", studentId, request.getSubject(), sessionCount);
                    performanceData.put("completedExercises", sessionCount);
                }
                
                // 获取最近练习记录
                String recentPracticeSql = 
                        "SELECT date, topic, score FROM student_practice_sessions " +
                        "WHERE student_id = ? AND subject = ? " +
                        "ORDER BY created_time DESC LIMIT 5";
                
                List<Map<String, Object>> recentPractices = jdbcTemplate.queryForList(
                        recentPracticeSql, studentId, request.getSubject());
                
                if (!recentPractices.isEmpty()) {
                    logger.info("查询到学生 {} 在 {} 学科的最近练习记录: {}", 
                            studentId, request.getSubject(), recentPractices.size());
                    performanceData.put("recentPractices", recentPractices);
                }
            } catch (Exception e) {
                logger.error("获取学生练习数据失败", e);
            }
            
            // 数据整合完成，记录最终要发送的数据
            logger.info("发送给AI分析的最终学生数据: {}", performanceData);
            
            // 调用包含学习数据的方法
            String response = aiTeachingService.analyzeStudentLevel(
                    studentId, 
                    request.getSubject(), 
                    request.getQuestion(), 
                    performanceData);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("analysis", response);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取AI助手反馈失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取AI助手反馈失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 将中文学科名称转换为数据库字段名
     */
    private String convertSubjectNameToField(String subjectName) {
        if (subjectName == null) return null;
        
        switch (subjectName) {
            case "语文": return "chinese";
            case "数学": return "math";
            case "英语": return "english";
            case "物理": return "physics";
            case "化学": return "chemistry";
            case "生物": return "biology";
            case "政治": return "politics";
            case "历史": return "history";
            case "地理": return "geography";
            default: return null;
        }
    }

    /**
     * 获取学习能力评估
     */
    @GetMapping("/ability-assessment")
    public ResponseEntity<?> getAbilityAssessment(
            @RequestHeader("Authorization") String token,
            @RequestParam String subject) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            Map<String, Object> assessmentData = aiTeachingService.generateAbilityAssessment(studentId, subject);
            
            logger.info("AI服务返回的原始数据: {}", assessmentData);
            
            // 转换为前端期望的格式
            Map<String, Object> formattedResponse = new HashMap<>();
            
            // 构造能力数组
            List<Map<String, Object>> abilities = new ArrayList<>();
            
            // 获取详细评估内容，用于提取针对性建议
            String assessmentDetails = "";
            if (assessmentData.containsKey("assessment_details")) {
                assessmentDetails = (String) assessmentData.get("assessment_details");
                logger.info("获取到评估详情: {}", assessmentDetails);
            } else {
                logger.warn("未找到assessment_details字段");
            }
            
            // 知识维度
            if (assessmentData.containsKey("knowledge_dimension")) {
                Map<String, Object> knowledgeAbility = new HashMap<>();
                float score = ((Number) assessmentData.get("knowledge_dimension")).floatValue() * 10; // 0-10分转为0-100分
                logger.info("知识维度得分(放大10倍): {}", score);
                knowledgeAbility.put("name", "知识维度");
                knowledgeAbility.put("score", score);
                knowledgeAbility.put("description", "对基础概念和理论的理解程度");
                
                // 提取建议（从assessment_details中提取相关部分）
                List<String> suggestions = new ArrayList<>();
                if (assessmentDetails.contains("知识") || assessmentDetails.contains("理解") || assessmentDetails.contains("记忆")) {
                    suggestions.add("加强对课本知识的理解和记忆");
                    suggestions.add("多做基础题，巩固知识点");
                } else {
                    suggestions.add("系统复习基础知识点");
                    suggestions.add("建立知识体系，加深理解");
                }
                knowledgeAbility.put("suggestions", suggestions);
                abilities.add(knowledgeAbility);
                logger.info("添加知识维度能力: {}", knowledgeAbility);
            } else {
                logger.warn("未找到knowledge_dimension字段");
            }
            
            // 应用维度
            if (assessmentData.containsKey("application_dimension")) {
                Map<String, Object> applicationAbility = new HashMap<>();
                float score = ((Number) assessmentData.get("application_dimension")).floatValue() * 10; // 0-10分转为0-100分
                logger.info("应用维度得分(放大10倍): {}", score);
                applicationAbility.put("name", "应用维度");
                applicationAbility.put("score", score);
                applicationAbility.put("description", "将知识应用到实际问题的能力");
                
                // 提取建议
                List<String> suggestions = new ArrayList<>();
                if (assessmentDetails.contains("应用") || assessmentDetails.contains("实际") || assessmentDetails.contains("解决问题")) {
                    suggestions.add("多做应用题，训练解题思路");
                    suggestions.add("尝试将所学知识应用到日常生活中");
                } else {
                    suggestions.add("加强知识点之间的联系，提高应用能力");
                    suggestions.add("尝试解决一些综合性问题");
                }
                applicationAbility.put("suggestions", suggestions);
                abilities.add(applicationAbility);
                logger.info("添加应用维度能力: {}", applicationAbility);
            } else {
                logger.warn("未找到application_dimension字段");
            }
            
            // 创新维度
            if (assessmentData.containsKey("innovation_dimension")) {
                Map<String, Object> innovationAbility = new HashMap<>();
                float score = ((Number) assessmentData.get("innovation_dimension")).floatValue() * 10; // 0-10分转为0-100分
                logger.info("创新维度得分(放大10倍): {}", score);
                innovationAbility.put("name", "创新维度");
                innovationAbility.put("score", score);
                innovationAbility.put("description", "创新思维和解决问题的独特性");
                
                // 提取建议
                List<String> suggestions = new ArrayList<>();
                if (assessmentDetails.contains("创新") || assessmentDetails.contains("创造") || assessmentDetails.contains("新颖")) {
                    suggestions.add("尝试用不同方法解决同一问题");
                    suggestions.add("多思考开放性问题");
                } else {
                    suggestions.add("培养发散思维，从多角度思考问题");
                    suggestions.add("参与创新性的学习活动");
                }
                innovationAbility.put("suggestions", suggestions);
                abilities.add(innovationAbility);
                logger.info("添加创新维度能力: {}", innovationAbility);
            } else {
                logger.warn("未找到innovation_dimension字段");
            }
            
            formattedResponse.put("abilities", abilities);
            logger.info("最终能力数组长度: {}", abilities.size());
            
            // 添加学习建议
            String suggestions = assessmentData.containsKey("recommendation") ? 
                                (String) assessmentData.get("recommendation") : 
                                "暂无学习建议";
            formattedResponse.put("suggestions", suggestions);
            
            // 不再添加临时进步趋势数据，由前端处理空数据情况
            formattedResponse.put("progressData", new ArrayList<>());
            
            logger.info("返回给前端的完整响应: {}", formattedResponse);
            return ResponseEntity.ok(formattedResponse);
        } catch (Exception e) {
            logger.error("获取能力评估失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取能力评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更新错题状态（已解决/未解决）
     */
    @PutMapping("/mistake-collection/{mistakeId}/status")
    public ResponseEntity<?> updateMistakeStatus(
            @RequestHeader("Authorization") String token,
            @PathVariable Long mistakeId,
            @RequestBody Map<String, Boolean> statusRequest) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean resolved = statusRequest.get("resolved");
            logger.info("更新错题状态 - 错题ID: {}, 学生ID: {}, 状态: {}", mistakeId, studentId, resolved ? "已解决" : "未解决");
            
            // 更新错题状态
            studentPracticeService.updateMistakeStatus(mistakeId, studentId, resolved);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", resolved ? "错题已标记为已解决" : "错题已标记为未解决");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新错题状态失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新错题状态失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 从错题本中删除错题
     */
    @DeleteMapping("/mistake-collection/{mistakeId}")
    public ResponseEntity<?> deleteFromMistakeCollection(
            @RequestHeader("Authorization") String token,
            @PathVariable Long mistakeId) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            logger.info("删除错题 - 错题ID: {}, 学生ID: {}", mistakeId, studentId);
            
            // 验证错题所属
            boolean isOwner = studentPracticeService.validateMistakeOwnership(mistakeId, studentId);
            if (!isOwner) {
                logger.error("学生[{}]无权限删除错题[{}]", studentId, mistakeId);
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权限删除此错题");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            // 删除错题
            studentPracticeService.removeFromMistakeCollection(mistakeId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错题已成功删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("删除错题失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 添加错题到错题本
     */
    @PostMapping("/mistake-collection/add")
    public ResponseEntity<?> addToMistakeCollection(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> mistakeData) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            logger.info("添加错题 - 学生ID: {}, 题目ID: {}", studentId, mistakeData.get("exerciseId"));
            
            // 创建错题对象
            StudentMistakeCollection mistake = new StudentMistakeCollection();
            mistake.setStudentId(studentId);
            
            // 设置exerciseId (必须)
            if (mistakeData.containsKey("exerciseId")) {
                Long exerciseId = Long.valueOf(mistakeData.get("exerciseId").toString());
                mistake.setExerciseId(exerciseId);
            } else {
                logger.error("添加错题失败: 缺少exerciseId");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "添加错题失败: 缺少exerciseId");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 设置subject (必须)
            if (mistakeData.containsKey("subject")) {
                mistake.setSubject(mistakeData.get("subject").toString());
            } else {
                logger.error("添加错题失败: 缺少subject");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "添加错题失败: 缺少subject");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 设置content (必须) - 对应数据库的question字段
            if (mistakeData.containsKey("content")) {
                mistake.setContent(mistakeData.get("content").toString());
            } else {
                logger.error("添加错题失败: 缺少content");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "添加错题失败: 缺少content");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 设置correctAnswer (必须)
            if (mistakeData.containsKey("correctAnswer")) {
                mistake.setCorrectAnswer(mistakeData.get("correctAnswer").toString());
            } else {
                logger.error("添加错题失败: 缺少correctAnswer");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "添加错题失败: 缺少correctAnswer");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 设置knowledgePoint (可选) - 对应数据库的topic字段
            if (mistakeData.containsKey("knowledgePoint")) {
                mistake.setKnowledgePoint(mistakeData.get("knowledgePoint").toString());
            } else {
                mistake.setKnowledgePoint("综合");
            }
            
            // 设置其他字段
            mistake.setMistakeCount(1);
            mistake.setLastMistakeTime(LocalDateTime.now());
            mistake.setCreateTime(LocalDateTime.now());
            
            // 保存错题
            studentPracticeService.addToMistakeCollection(mistake);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错题已成功添加到错题本");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("添加错题失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "添加错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更新学生个人信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateStudentProfile(
            @RequestHeader("Authorization") String token,
            @RequestBody ProfileUpdateRequest profileRequest) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("更新学生个人信息失败：未找到学生ID");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "未找到学生ID，请重新登录");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 获取学生信息并更新
            Student student = studentService.getStudentByStudentId(studentId);
            if (student == null) {
                logger.error("更新学生个人信息失败：学生ID {} 不存在", studentId);
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "学生不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            
            // 更新学生信息
            student.setName(profileRequest.getName());
            student.setPhone(profileRequest.getPhoneNumber());
            student.setEmail(profileRequest.getEmail());
            
            // 保存更新后的学生信息
            Student updatedStudent = studentService.saveStudent(student);
            logger.info("成功更新学生 {} 的个人信息", studentId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "个人信息更新成功");
            response.put("data", updatedStudent);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新学生个人信息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新学生个人信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更新学生密码
     */
    @PutMapping("/password")
    public ResponseEntity<?> updatePassword(
            @RequestHeader("Authorization") String token,
            @RequestBody PasswordUpdateRequest passwordRequest) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("更新密码失败：未找到学生ID");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "未找到学生ID，请重新登录");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 更新密码
            boolean updated = studentService.updatePassword(
                    studentId,
                    passwordRequest.getCurrentPassword(),
                    passwordRequest.getNewPassword()
            );
            
            if (updated) {
                logger.info("成功更新学生 {} 的密码", studentId);
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "密码更新成功");
                return ResponseEntity.ok(response);
            } else {
                logger.warn("更新密码失败：当前密码不正确，学生ID: {}", studentId);
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "当前密码不正确");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }
        } catch (Exception e) {
            logger.error("更新密码失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新密码失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更新学习进度
     */
    @PostMapping("/update-learning-progress")
    public ResponseEntity<?> updateLearningProgress(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> progressData) {
        try {
            String studentId = studentService.getStudentIdFromToken(token);
            
            if (studentId == null) {
                logger.error("无效的Token或非学生用户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无效的Token或非学生用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            logger.info("更新学习进度 - 学生ID: {}, 学科: {}", studentId, progressData.get("subject"));
            
            String subject = (String) progressData.get("subject");
            String knowledgePoint = (String) progressData.get("knowledgePoint");
            Boolean isCorrect = (Boolean) progressData.get("isCorrect");
            
            // 调用学生练习服务更新学习进度
            studentPracticeService.updateLearningProgress(studentId, subject, knowledgePoint, isCorrect);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "学习进度已更新");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新学习进度失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新学习进度失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 